<template>
  <div class="admin-dashboard">
    <!-- 复用管理员侧边栏 -->
    <div class="admin-sidebar">
      <div class="admin-sidebar-header">
        <h2>管理控制台</h2>
      </div>
      <ul class="admin-menu">
        <li>
          <router-link to="/admin/dashboard" class="menu-item" active-class="active">
            <span class="menu-icon">📊</span>
            <span class="menu-text">仪表盘</span>
          </router-link>
        </li>
        <li>
          <router-link to="/admin/users" class="menu-item" active-class="active">
            <span class="menu-icon">👥</span>
            <span class="menu-text">用户管理</span>
          </router-link>
        </li>
        <li>
          <router-link to="/admin/questions" class="menu-item" active-class="active">
            <span class="menu-icon">❓</span>
            <span class="menu-text">问答管理</span>
          </router-link>
        </li>
        <li>
          <router-link to="/admin/stories" class="menu-item" active-class="active">
            <span class="menu-icon">📖</span>
            <span class="menu-text">故事管理</span>
          </router-link>
        </li>
      </ul>
      <div class="admin-sidebar-footer">
        <button @click="handleLogout" class="logout-btn">退出登录</button>
      </div>
    </div>

    <!-- 管理员主内容区 -->
    <div class="admin-main-content">
      <div class="admin-header">
        <h1>用户管理</h1>
        <div class="admin-user-info">
          <span>欢迎，{{ currentUser?.username }}</span>
        </div>
      </div>
      
      <!-- 搜索和筛选 -->
      <div class="filter-section">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索用户名或邮箱"
          class="search-input"
        />
        <select v-model="userTypeFilter" class="filter-select">
          <option value="all">全部用户</option>
          <option value="member">会员用户</option>
          <option value="non-member">非会员用户</option>
          <option value="admin">管理员</option>
        </select>
      </div>

      <!-- 用户列表 -->
      <div class="users-table-container">
        <table class="users-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>用户名</th>
              <th>邮箱</th>
              <th>会员状态</th>
              <th>管理员</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in filteredUsers" :key="user.id">
              <td>{{ user.id }}</td>
              <td>{{ user.username }}</td>
              <td>{{ user.email }}</td>
              <td>
                <span :class="['status-badge', user.isMember ? 'member' : 'non-member']">
                  {{ user.isMember ? '会员' : '非会员' }}
                </span>
              </td>
              <td>
                <span :class="['status-badge', user.isAdmin ? 'admin' : '']">
                  {{ user.isAdmin ? '是' : '否' }}
                </span>
              </td>
              <td>
                <button @click="editUser(user)" class="action-btn edit-btn">编辑</button>
                <button @click="deleteUser(user.id)" class="action-btn delete-btn">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
        <p v-if="filteredUsers.length === 0" class="no-data">没有找到符合条件的用户</p>
      </div>

      <!-- 编辑用户对话框 -->
      <div v-if="showEditModal" class="modal-overlay" @click.self="closeModal">
        <div class="modal-content">
          <h3>编辑用户</h3>
          <div class="form-group">
            <label for="edit-username">用户名</label>
            <input 
              type="text" 
              id="edit-username" 
              v-model="editingUser.username" 
              disabled
            />
          </div>
          <div class="form-group">
            <label for="edit-email">邮箱</label>
            <input 
              type="email" 
              id="edit-email" 
              v-model="editingUser.email" 
            />
          </div>
          <div class="form-group">
            <label>
              <input 
                type="checkbox" 
                v-model="editingUser.isMember" 
              />
              会员用户
            </label>
          </div>
          <div class="form-group">
            <label>
              <input 
                type="checkbox" 
                v-model="editingUser.isAdmin" 
                :disabled="editingUser.username === 'admin'"
              />
              管理员权限
              <span v-if="editingUser.username === 'admin'" class="disabled-hint">(默认管理员不可修改)</span>
            </label>
          </div>
          <div class="modal-actions">
            <button @click="saveUser" class="save-btn">保存</button>
            <button @click="closeModal" class="cancel-btn">取消</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { userStore } from '../../stores/user'

export default {
  name: 'UsersView',
  data() {
    return {
      users: [],
      searchQuery: '',
      userTypeFilter: 'all',
      showEditModal: false,
      editingUser: {},
      currentUser: null
    }
  },
  computed: {
    userState() {
      const state = userStore.getState()
      return state
    },
    filteredUsers() {
      let result = [...this.users]
      
      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(user => 
          user.username.toLowerCase().includes(query) || 
          user.email.toLowerCase().includes(query)
        )
      }
      
      // 用户类型过滤
      if (this.userTypeFilter === 'member') {
        result = result.filter(user => user.isMember)
      } else if (this.userTypeFilter === 'non-member') {
        result = result.filter(user => !user.isMember)
      } else if (this.userTypeFilter === 'admin') {
        result = result.filter(user => user.isAdmin)
      }
      
      return result
    }
  },
  mounted() {
    // 检查用户是否已登录且是管理员
    this.checkAdminAccess()
    this.loadUsers()
  },
  methods: {
    checkAdminAccess() {
      if (!this.userState.isAuthenticated || !this.userState.currentUser.isAdmin) {
        this.$router.push('/admin/login')
      } else {
        this.currentUser = this.userState.currentUser
      }
    },
    loadUsers() {
      // 模拟从API获取用户数据
      // 这里我们直接使用userStore中的users数组
      // 注意：在实际项目中，我们可能需要从API获取
      this.users = [
        { id: 1, username: 'testuser', email: 'test@example.com', isMember: false, isAdmin: false },
        { id: 2, username: 'memberuser', email: 'member@example.com', isMember: true, isAdmin: false },
        { id: 3, username: 'admin', email: 'admin@example.com', isMember: true, isAdmin: true },
        { id: 4, username: 'user4', email: 'user4@example.com', isMember: false, isAdmin: false },
        { id: 5, username: 'user5', email: 'user5@example.com', isMember: true, isAdmin: false }
      ]
    },
    editUser(user) {
      // 深拷贝用户对象，避免直接修改原数据
      this.editingUser = JSON.parse(JSON.stringify(user))
      this.showEditModal = true
    },
    saveUser() {
      // 模拟保存用户数据
      const index = this.users.findIndex(u => u.id === this.editingUser.id)
      if (index !== -1) {
        this.users[index] = { ...this.editingUser }
      }
      this.closeModal()
    },
    deleteUser(userId) {
      if (confirm('确定要删除这个用户吗？')) {
        // 模拟删除用户
        this.users = this.users.filter(user => user.id !== userId)
      }
    },
    closeModal() {
      this.showEditModal = false
      this.editingUser = {}
    },
    handleLogout() {
      userStore.logout()
      this.$router.push('/admin/login')
    }
  }
}
</script>

<style scoped>
/* 复用管理员侧边栏样式 */
.admin-sidebar {
  width: 250px;
  background-color: #2c3e50;
  color: white;
  padding: 20px 0;
}

.admin-sidebar-header {
  padding: 0 20px 30px;
  border-bottom: 1px solid #34495e;
}

.admin-sidebar-header h2 {
  margin: 0;
  font-size: 18px;
}

.admin-menu {
  list-style: none;
  padding: 0;
  margin: 20px 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  color: #bdc3c7;
  text-decoration: none;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #34495e;
  color: white;
}

.menu-item.active {
  background-color: #4CAF50;
  color: white;
}

.menu-icon {
  margin-right: 15px;
  font-size: 18px;
}

.admin-sidebar-footer {
  padding: 20px;
  border-top: 1px solid #34495e;
  margin-top: auto;
}

.logout-btn {
  width: 100%;
  padding: 10px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.logout-btn:hover {
  background-color: #c0392b;
}

/* 管理员主内容区 */
.admin-main-content {
  flex: 1;
  padding: 20px 30px;
  overflow-y: auto;
  max-width: 100%;
  overflow-x: auto;
}

.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.admin-header h1 {
  margin: 0;
  color: #2c3e50;
}

.admin-user-info {
  color: #7f8c8d;
}

/* 筛选部分 */
.filter-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.filter-select {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
}

/* 用户表格 */
.users-table-container {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow-x: auto;
}

.users-table {
  width: 100%;
  border-collapse: collapse;
}

.users-table th,
.users-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ecf0f1;
}

.users-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

/* 状态标签 */
.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.member {
  background-color: #e3f2fd;
  color: #1976d2;
}

.status-badge.non-member {
  background-color: #f5f5f5;
  color: #757575;
}

.status-badge.admin {
  background-color: #e8f5e9;
  color: #388e3c;
}

/* 操作按钮 */
.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-right: 5px;
  transition: background-color 0.3s;
}

.edit-btn {
  background-color: #2196f3;
  color: white;
}

.edit-btn:hover {
  background-color: #1976d2;
}

.delete-btn {
  background-color: #f44336;
  color: white;
}

.delete-btn:hover {
  background-color: #d32f2f;
}

.no-data {
  text-align: center;
  color: #7f8c8d;
  padding: 20px;
}

/* 模态框 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-content h3 {
  margin: 0 0 20px;
  color: #2c3e50;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #555;
}

.form-group input[type="text"],
.form-group input[type="email"] {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group input[type="checkbox"] {
  margin-right: 8px;
}

.disabled-hint {
  color: #999;
  font-size: 12px;
  margin-left: 5px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.save-btn {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.save-btn:hover {
  background-color: #45a049;
}

.cancel-btn {
  padding: 10px 20px;
  background-color: #f1f1f1;
  color: #333;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}
</style>